<!--
  上传组件
  wdz
  2019年12月23日
-->

<template lang="pug">
  el-upload(
  :action="action"
  :headers="headers"
  :multiple="false"
  :on-success="handleSuccess"
  :on-preview="handlePreview"
  :on-remove="handleRemove"
  :before-remove="beforeRemove"
  :before-upload="beforeUpload"
  :limit="limit"
  :on-exceed="handleExceed"
  :file-list="fileListData"
  :list-type="listType"
  ref="upload"
  :disabled="disabled"
  )
    el-button(size="small" :type="btnType" style="font-size:14px" :disabled="disabled") {{btnText}}
    div(slot="tip" class="el-upload__tip" v-if="tipText") {{tipText}}
</template>
<script type="text/ecmascript-6">
  import Cache from '../common/cache.js'
  import Vue from 'vue'
  // import Message from '../../../src/common/message'
  export default {
    name: 'Upload',
    props: {
      action: { // 文件上传路径
        type: String, default: ''
      },
      fileType: { // 文件格式
        type: String
      },
      onlyMedia: {
        type: Boolean,
        default: true
      },
      btnText: { // 上传按钮文本
        type: String, default: '+'
      },
      btnType: { // 上传按钮类型
        type: String, default: 'text'
      },
      limit: { // 上传数量限制
        type: Number, default: 100
      },
      tipText: { // 上传提示文字
        type: String, default: ''
      },
      fileList: { // 文件回显列表
        type: Array,
        default() {
          return []
        }
      },
      listType: { // 文件回显列表类型
        type: String,
        default: 'text'
      },
      disabled: { // 是否禁用
        type: Boolean,
        default: false
      }
    },
    mounted() {
    },
    data() {
      return {
        // https://jsonplaceholder.typicode.com/posts/
        file: null,
        headers: {'access_token': Cache.get('access_token'), 'jsessionid': Cache.get('user_token')}, // 上传时Ajax的header
        fileListData: this.fileList, // 文件回显 从父组件传入
        isUpload: true, // 上传状态
        dialogImageUrl: '', // 图片预览弹窗中的图片路径
        dialogVisible: false // 图片预览弹窗显示状态
      }
    },
    methods: {
      // 上传后删除功能
      handleRemove(file, fileList) {
        console.log(file, fileList)
        if (file.status === 'success') {
          let attachmentId = ''
          let rev = ''
          if (file.response) {
            attachmentId = file.response.attachmentId
            rev = file.response.attachmentRev
          } else {
            let pathParts = file.url.split('/')
            pathParts.pop()
            attachmentId = pathParts.pop()
          }
          // 删除couchdb数据库中附件
          if (attachmentId !== '' && rev !== '') {
            Vue.axios.request({
              method: 'DELETE',
              url: '/camel/rest/couchdb',
              params: {'id': attachmentId, 'rev': rev},
              data: {}
            }).then((response) => {
              console.log(response.data.success)
            })
          }
          if (this.limit === 1) {
            this.$emit('filePath', null, null)
          } else {
            this.$emit('fileDelete', null, null)
          }
        }
      },
      // 上传之前的文件验证
      beforeUpload(file) {
        let isJPG = false
        // let isLt2M = false
        let isVideo = false
        let isFile = false
        if (file.name.indexOf(' ') > -1) {
          this.$message.error('文件名含有空格，请删除空格后重新上传')
          return false
        } else if (this.onlyMedia) {
          if (this.fileType === 'img') {
            isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
            // isLt2M = file.size / 1024 / 1024 < 2
            isVideo = true
            isFile = true
            if (!isJPG) {
              // Message.error('上传图片只能是 JPG 或 PNG 格式!')
              this.fileListData = []
              return
            }
          } else if (this.fileType === 'video') {
            isVideo = file.type === 'video/avi' || file.type === 'video/mp4'
            isJPG = true
            // isLt2M = true
            isFile = true
            if (!isVideo) {
              // Message.error('上传视频只能是 MP4 或 avi 格式!')
              this.fileListData = []
              return
            }
          } else if (this.fileType === 'file') {
            isFile = file.type === 'application/vnd.ms-powerpoint' || file.type === 'application/msword' || file.type === 'application/vnd.ms-excel' || file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' || file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || file.type === 'application/vnd.openxmlformats-officedocument.presentationml.presentation' || file.type === 'application/pdf'
            isJPG = true
            // isLt2M = true
            isVideo = true
            if (!isFile) {
              // Message.error('上传音频只能是 JPG 或 PNG 格式!')
              this.fileListData = []
              return
            }
          }
          if (!isJPG || !isVideo || !isFile) {
            this.isUpload = false
            this.fileListData = []
          }
          return isJPG && isVideo && isFile
        } else {
          return true
        }
      },
      // 上传成功后获取文件路径并传入父组件
      handleSuccess(response, file, fileList) {
        console.log('--file-status---', response.attachmentPath, response.attachmentName)
        this.$emit('filePath', response.attachmentPath, response.attachmentName)
      },
      handlePreview(file) {
        // console.log(file)
      },
      handleExceed(files, fileList) {
        // Message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
      },
      // 删除前提示
      beforeRemove(file, fileList) {
        console.log(file.name.indexOf(' '))
        if (file.name.indexOf(' ') === -1) {
          return this.$confirm(`确定移除 ` + file.name + `？`)
        }
      },
      // 清空上传组件列表
      clearFiles() {
        this.$refs.upload.clearFiles()
      }
    }
  }
</script>
<style scoped lang="stylus" type="text/stylus">
</style>
